import axios from 'axios'
import store from '@/store'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import notification from 'ant-design-vue/es/notification'
import message from 'ant-design-vue/es/message'
import { VueAxios } from './axios'

// 创建 axios 实例
const request = axios.create({
	/* headers: {
	   'Content-Type': 'text/html; charset=UTF-8',
	}, */
	// API 请求的默认前缀
	baseURL: process.env.VUE_APP_API_BASE_URL,
	timeout: 6000 // 请求超时时间
})

// 异常拦截处理器
const errorHandler = error => {
  console.log('error', error)
  if (error.response) {
    // const data = error.response.data
    // if (error.response.status === 403) {
    //   notification.error({
    //     message: '权限校验',
    //     description: data.message
    //   })
    // }
    if (error.response.status === 404) {
      notification.error({ message: '系统提示', description: '很抱歉，请求URL不存在!', duration: 4 })
    }
    if (error.response.status >= 500) {
      notification.error({
        message: '错误',
        description: '服务器错误,请联系管理员'
      })
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  const token = storage.get(ACCESS_TOKEN)
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers['token'] = token;
  }
  // 解决ie浏览器中get请求被缓存的问题
  if (config.method === 'get') {
    config.params = {
      t: new Date().getTime(),
      ...config.params
    }
  }
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use(response => {
  // console.log('response', response)
  const status = response.data.status
  const msg = response.data.msg
  const token = storage.get(ACCESS_TOKEN)

  if (status === 1) {
    message.warning(msg)
    return Promise.reject(new Error(msg))
  } else if (status === 300) {
    notification.error({
      message: '权限校验',
      description: msg
    })
    if (token) {
      store.dispatch('Logout').then(() => {
        setTimeout(() => {
          window.location.reload()
        }, 1500)
      })
    }
    return Promise.reject(new Error('Unauthorized'))
  } else {
    return response.data
  }
}, errorHandler)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export { installer as VueAxios, request as axios }
